package com.bdqn.t330.ch11.controller;


import com.bdqn.t330.ch11.entity.SysUser;
import com.bdqn.t330.ch11.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    UserService userService;

    @RequestMapping("/index")
    public String index() {
        return "/login";
    }

    @RequestMapping("/login")
    public String login(String userCode, String userPassword, HttpSession session) {
        SysUser sysUser = new SysUser();
        sysUser.setUserCode(userCode);
        sysUser.setUserPassword(userPassword);
        SysUser loginUser = userService.loginBiz(sysUser);
        if (loginUser != null) {
            session.setAttribute("sysUser", loginUser);
            return "/frame";
        } else {
            throw new RuntimeException("登录异常");
        }
    }

    //声明一个局部异常
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest request) {
        request.setAttribute("e", e);
        return "/error";
    }

    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
        session.removeAttribute("sysUser");
        return "redirect: index";
    }
}
